﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace ByteSite.Web.tools
{
    /// <summary>
    /// websocket 的摘要说明
    /// </summary>
    public class websocket : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.UserAgent.Contains("ByteSite"))
            {
                if (context.Request.Files != null)
                {
                    if (context.Request.Files.Count > 0)
                    {
                        //保存文件到服务器
                        HttpFileCollection uploadFiles = context.Request.Files;
                        try
                        {
                            for (int i = 0; i < uploadFiles.Count; i++)
                            {
                                HttpPostedFile postedFile = uploadFiles[i];
                                postedFile.SaveAs(context.Server.MapPath("~/ClientFiles/") + postedFile.FileName);
                            }

                        }
                        catch (System.Exception Ex)
                        {

                        }

                    }
                }


                Stream s = context.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                string data = Encoding.UTF8.GetString(b).TrimStart('\r').TrimStart('\n');
                if (data.IndexOf("\r\n")>0)
                {
                    string boundary = data.Substring(2, data.IndexOf("\r\n") - 2);

                    string[] _paras = Common.Utils.SplitString(data, "--" + boundary);

                    foreach (string p in _paras)
                    {
                        if (!string.IsNullOrEmpty(p) && p != "--\r\n")
                        {
                            if (p.IndexOf("Content-Type:application/octet-stream") > 0)
                            {
                                //文件流
                            }
                            else
                            {
                                Common.LoggerHelper.Error(p.TrimStart('\r').TrimStart('\n').TrimEnd('\n').TrimEnd('\r'));
                                //数据

                            }
                        }
                    }
                }
                else
                {
                    Common.LoggerHelper.Error(data);
                }

                


            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}